#include <stdio.h>
#include "MeshConverter.h"
#include "Options.h"

int wmain(int argc, LPWSTR args[])
{
	HRESULT hr = S_OK;
	LPDIRECT3DDEVICE9 pDevice = NULL;
	LPD3DXMATERIAL materials = NULL;
	LPD3DXEFFECT effects = NULL;
	LPD3DXMESH mesh = NULL;
	DWORD nMaterials = 0;
	SDKMESH sdkMesh;
	Options options;

	ZeroMemory(&sdkMesh, sizeof(SDKMESH));
	ZeroMemory(&options, sizeof(Options));

	// Read Options
	hr = ReadOptions(argc, args, &options);
	if (FAILED(hr)) goto END;
	// Initialize
	hr = Initialize(options, &pDevice);
	if (FAILED(hr)) goto END;
	// Load
	hr = Load(pDevice, options, &materials, &nMaterials, &mesh);
	if (FAILED(hr)) goto END;
	// Convert
	hr = Convert(materials, nMaterials, mesh, options, &sdkMesh);
	if (FAILED(hr)) goto END;
	// Save
	hr = Save(sdkMesh, options);
	if (FAILED(hr)) goto END;

END:
	pDevice->Release();
	if (options.inputPath != NULL) free(options.inputPath);
	if (options.outputPath != NULL) free(options.outputPath);
	if (options.normalTexture != NULL) free(options.normalTexture);
	if (options.specularTexture != NULL) free(options.specularTexture);
	if (sdkMesh.materials != NULL) free(sdkMesh.materials);
	if (sdkMesh.meshes != NULL) free(sdkMesh.meshes);
	if (sdkMesh.meshHeader != NULL) free(sdkMesh.meshHeader);
	if (sdkMesh.subsets != NULL) free(sdkMesh.subsets);
	if (sdkMesh.vertexHeaders != NULL) free(sdkMesh.vertexHeaders);
	if (sdkMesh.indexHeaders != NULL) free(sdkMesh.indexHeaders);
	if (sdkMesh.indexDatas != NULL) free(sdkMesh.indexDatas);
	if (sdkMesh.vertexDatas != NULL) free(sdkMesh.vertexDatas);
	if (materials != NULL) 
	{
		for (UINT i = 0; i < nMaterials; i++)
		{
			if (materials[i].pTextureFilename != NULL) free(materials[i].pTextureFilename);
		}
		free(materials);
	}
	if (effects != NULL) effects->Release();
	if (mesh != NULL) mesh->Release();

	if (FAILED(hr)) return 1;

	return 0;	
}